package com.software.frontend;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.software.frontend.fragments.Add_MainFragment;
import com.software.frontend.fragments.Mine_MainFragment;
import com.software.frontend.fragments.YouYouJIan_MainFragment;
import com.software.frontend.loginAndRegist.entity.UserExtends;
import com.software.frontend.videoEdit.VideoEditActivity;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    FrameLayout frameLayout;
    TextView youYouJian, mine;
    LinearLayout youYouJian_LinearLayout, add_LinearLayout, mine_LinearLayout;
    ImageView add;
    public static UserExtends userExtends;
    SharedPreferences sp;
    SharedPreferences.Editor editor;
    private String getUserExtendsLocation = "center/findUserExtends";
    private OkHttpClient okHttpClient = new OkHttpClient();
    private Gson gson = new Gson();

    private static int UN_LOGIN = 0;
    private static int LOGIN = 1;
    Message msg = new Message();
    private final Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.arg1 == UN_LOGIN){
                editor.putString("isLogin", "F");
                editor.remove("userId");
                editor.commit();
                userExtends = null;
            }else if (userExtends == null) {
                Toast.makeText(MainActivity.this, "您的账户登陆异常，已为您退出登陆", Toast.LENGTH_SHORT).show();
            }
            mine_mainFragment.setmUserExtends(userExtends);
        }
    };
    /**
     * 实例化要用到的Fragment页面
     */
    Add_MainFragment add_mainFragment;
    Mine_MainFragment mine_mainFragment;
    YouYouJIan_MainFragment youYouJIan_mainFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initSelfData();
        initViews();
        initFragments();




//        startWhichActivity(VideoEditActivity.class);
//        startWhichActivity(SearchMovieRequestActivity.class);
//        startWhichActivity(LoginByPhoneAndPasswordActivity.class);

    }

    private void startWhichActivity(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }

    private void initSelfData() {
        sp = MainActivity.this.getSharedPreferences("loginInformation", Context.MODE_PRIVATE);
        editor = sp.edit();
        if ((UserExtends) getIntent().getSerializableExtra("usersExtends") != null){
            userExtends = (UserExtends) getIntent().getSerializableExtra("usersExtends");
            editor.putString("isLogin","T");
            editor.putString("userId", userExtends.getId().toString());
            editor.commit();
            msg.arg1 = LOGIN;
            msg.arg2 = 1;
        }else {
            String isLogin = sp.getString("isLogin", "F");
            String userId = sp.getString("userId", "");
            if (isLogin != null && isLogin.equals("T") && userId != null && !userId.equals("")){
                FormBody formBody = new FormBody.Builder()
                        .add("id", userId)
                        .build();
                Request request = new Request.Builder().url(getResources().getString(R.string.localhost) + getUserExtendsLocation).post(formBody).build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        Log.i("onFailure", "访问失败");
                        msg.arg1 = UN_LOGIN;
                        msg.arg2 = 0;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String s = response.body().string();
                        userExtends = gson.fromJson(s, UserExtends.class);
                        msg.arg2 = 0;
                        msg.arg1 = LOGIN;
                        handler.sendMessage(msg);
                        System.out.println("success");
                    }
                });
            }else {
                msg.arg1 = UN_LOGIN;
                msg.arg2 = 1;
            }
            if (msg.arg2 == 1) {
                handler.sendMessage(msg);
            }
        }

    }

    private void initViews() {
        frameLayout = (FrameLayout) findViewById(R.id.main_fragment);
        youYouJian = (TextView) findViewById(R.id.mian_buttom_youYouJian);
        mine = (TextView) findViewById(R.id.mian_buttom_Mine);
        add = (ImageView) findViewById(R.id.main_buttom_add);
        youYouJian_LinearLayout = (LinearLayout) findViewById(R.id.main_buttom_youYouJian_Linear);
        add_LinearLayout = (LinearLayout) findViewById(R.id.main_buttom_add_Linear);
        mine_LinearLayout = (LinearLayout) findViewById(R.id.main_buttom_mine_Linear);

        int int_color_selected = ContextCompat.getColor(this, R.color.selected);
        int int_color_white = ContextCompat.getColor(this, R.color.white);

        youYouJian.setTextColor(int_color_selected);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager supportFragmentManager = MainActivity.this.getSupportFragmentManager();
                switch (v.getId()) {
                    case R.id.main_buttom_youYouJian_Linear:
                        youYouJian.setTextColor(int_color_selected);
                        add.setImageResource(R.mipmap.main_buttom_add);
                        mine.setTextColor(int_color_white);
                        supportFragmentManager
                                .beginTransaction()
                                .show(youYouJIan_mainFragment)
                                .hide(add_mainFragment)
                                .hide(mine_mainFragment)
                                .commit();
                        break;
                    case R.id.main_buttom_add_Linear:
                        startActivity(new Intent(getApplicationContext(), VideoEditActivity.class));
                        /*youYouJian.setTextColor(int_color_white);
                        add.setImageResource(R.mipmap.main_buttom_add_selected);
                        mine.setTextColor(int_color_white);
                        supportFragmentManager
                                .beginTransaction()
                                .hide(youYouJIan_mainFragment)
                                .show(add_mainFragment)
                                .hide(mine_mainFragment)
                                .commit();*/
                        break;
                    case R.id.main_buttom_mine_Linear:
                        youYouJian.setTextColor(int_color_white);
                        add.setImageResource(R.mipmap.main_buttom_add);
                        mine.setTextColor(int_color_selected);
                        supportFragmentManager
                                .beginTransaction()
                                .hide(youYouJIan_mainFragment)
                                .hide(add_mainFragment)
                                .show(mine_mainFragment)
                                .commit();
                        break;
                }
            }
        };

        youYouJian_LinearLayout.setOnClickListener(onClickListener);
        add_LinearLayout.setOnClickListener(onClickListener);
        mine_LinearLayout.setOnClickListener(onClickListener);



    }

    private void initFragments() {

        /**
         * 在此处修改Fragment池中的页面
         * 用.add(R.id.main_fragment, 实例化的Fragment页面)
         * 记得hide
         */
        add_mainFragment = new Add_MainFragment();
        mine_mainFragment = Mine_MainFragment.newInstance(userExtends);
        youYouJIan_mainFragment = new YouYouJIan_MainFragment();
        this.getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.main_fragment, youYouJIan_mainFragment)
                .add(R.id.main_fragment, add_mainFragment)
                .hide(add_mainFragment)
                .add(R.id.main_fragment, mine_mainFragment)
                .hide(mine_mainFragment)
                .commit();
    }

}

